package com.aidex.biz.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.aidex.biz.domain.Customer;
import com.aidex.biz.domain.CustomerDongtai;
import com.aidex.biz.domain.bo.IndexBo;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.domain.vo.OneSelfStatisticVo;
import com.aidex.biz.domain.vo.OneSelfStatisticZongVo;
import com.aidex.biz.domain.vo.OrgTypeStatisticVo;
import com.aidex.biz.service.CustomerDongtaiService;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sql.SqlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.entity.SysDept;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.framework.cache.DeptUtils;
import com.aidex.framework.cache.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.biz.mapper.JinjianBillMapper;
import com.aidex.biz.domain.JinjianBill;
import com.aidex.biz.service.JinjianBillService;
import org.springframework.transaction.annotation.Transactional;
import com.aidex.common.utils.NumberUtils;

/**
 * 费用管理Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-12-17
 */
@Service
@Transactional(readOnly = true)
public class JinjianBillServiceImpl extends BaseServiceImpl<JinjianBillMapper, JinjianBill> implements JinjianBillService {
    private static final Logger log = LoggerFactory.getLogger(JinjianBillServiceImpl.class);

    @Autowired
    private CustomerDongtaiService customerDongtaiService;

    /**
     * 获取单条数据
     *
     * @param jinjianBill 费用管理
     * @return 费用管理
     */
    @Override
    public JinjianBill get(JinjianBill jinjianBill) {
        JinjianBill dto = super.get(jinjianBill);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 费用管理id
     * @return 费用管理
     */
    @Override
    public JinjianBill get(String id) {
        JinjianBill dto = super.get(id);
        return dto;
    }


    /**
     * 查询费用管理列表
     *
     * @param jinjianBill 费用管理
     * @return 费用管理
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<JinjianBill> findList(JinjianBill jinjianBill) {
        return super.findList(jinjianBill);
    }

    /**
     * 分页查询费用管理列表
     *
     * @param jinjianBill 费用管理
     * @return 费用管理
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<JinjianBill> findPage(JinjianBill jinjianBill) {
        return super.findPage(jinjianBill);
    }

    /**
     * 保存费用管理
     *
     * @param jinjianBill
     * @return 结果
     */
    @Override
    public boolean save(JinjianBill jinjianBill) {
        return super.save(jinjianBill);
    }


    /**
     * 删除费用管理信息
     *
     * @param jinjianBill
     * @return 结果
     */
    @Override
    public boolean remove(JinjianBill jinjianBill) {
        return super.remove(jinjianBill);
    }

    /**
     * 批量删除费用管理
     *
     * @param ids 需要删除的费用管理ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteJinjianBillByIds(String[] ids) {
        return mapper.deleteJinjianBillByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param jinjianBill 费用管理
     * @return 结果
     */
    @Override
    public int findMaxSort(JinjianBill jinjianBill) {
        return NumberUtils.nextOrder(mapper.findMaxSort(jinjianBill));
    }

    @Override
    public JinjianBill getByJinjianId(String jinjianId) {
        JinjianBill jinjianBill = new JinjianBill();
        jinjianBill.setJinjianId(jinjianId);
        return mapper.getByJinjianId(jinjianBill);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<OrgTypeStatisticVo> orgTypeStatistic(JinjianBill jinjianBill) {
        PageDomain page = jinjianBill.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.orgTypeStatistic(jinjianBill));
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public OrgTypeStatisticVo sumOrgTypeStatistic(JinjianBill jinjianBill) {
        return mapper.sumOrgTypeStatistic(jinjianBill);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<OrgTypeStatisticVo> ExportOrgTypeStatistic(JinjianBill jinjianBill) {
        return mapper.orgTypeStatistic(jinjianBill);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<OneSelfStatisticVo> oneSelfStatistic(JinjianBill jinjianBill) {
        PageDomain page = jinjianBill.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.oneSelfStatistic(jinjianBill));
    }

    @Override
    public OneSelfStatisticZongVo oneSelfZongStatistic(JinjianBill jinjianBill) {
        return mapper.oneSelfZongStatistic(jinjianBill);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public Map<String, Objects> indexDataShow(IndexBo indexBo) {
        String sql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')";//当前月
        String hbsql = "DATE_FORMAT(a.create_time,'%y%m') =  DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH),'%y%m')";//上个月
        if (StringUtils.isEmpty(indexBo.getDateRange())) {
            switch (indexBo.getDateText()) {
                case "toDay":
                    sql = "DATE(a.create_time) = CURDATE()";
                    hbsql = "DATE(a.create_time) = CURDATE()-1";
                    break;
                case "tomorrow":
                    sql = "DATE_FORMAT(a.create_time,'%y%m%d') = DATE_FORMAT(CURDATE() - INTERVAL 1 DAY,'%y%m%d')";
                    hbsql = "DATE_FORMAT(a.create_time,'%y%m%d') = DATE_FORMAT(CURDATE() - INTERVAL 2 DAY,'%y%m%d')";
                    break;
                case "toWeek":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) AND WEEK(a.create_time) = WEEK(CURDATE())";
                    hbsql = "YEAR(a.create_time) = YEAR(CURDATE()) AND WEEK(a.create_time) = WEEK(CURDATE())-1";
                    break;
                case "lastMonth":
                    sql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')-1";
                    hbsql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')-2";
                    break;
                case "toQuarter":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) and QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) ";
                    hbsql = "YEAR(a.create_time) = YEAR(CURDATE())-1 and QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) -1";
                    break;
                case "lastQuarter":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) -1 and QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) - 1";
                    hbsql = "YEAR(a.create_time) = YEAR(CURDATE()) -2 and QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) - 2";
                    break;
                case "toYear":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE())";
                    hbsql = "YEAR(a.create_time) = YEAR(CURDATE()) - 1";
                    break;
                case "lastYear":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) - 1";
                    hbsql = "YEAR(a.create_time) = YEAR(CURDATE()) - 2";//去年环比 就是和前年比
                    break;
            }
        } else {
            if (indexBo.getDateRange().length == 2) {
                sql =
                        "date_format(a.create_time,'%y%m%d') >= date_format('" + indexBo.getDateRange()[0] + "'," + "'%y%m" +
                                "%d')" +
                                "AND date_format(a.create_time,'%y%m%d') <= date_format('" + indexBo.getDateRange()[1] +
                                "','%y%m%d')";
                hbsql = "DATE_FORMAT(a.create_time,'%y%m') =  DATE_FORMAT(DATE_SUB('" + indexBo.getDateRange()[0] + "', INTERVAL 1 MONTH)," +
                        "'%y%m')";
            }

        }


        indexBo.setSearchDateSql("and " + sql);
        indexBo.setSearchDateSqlHb("and " + hbsql);
        return mapper.indexDataShow(indexBo);
    }

    @Override
    public List<Map<String, Object>> indexPaiHangBangSelf(IndexBo indexBo) {

        String sql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')";
        switch (indexBo.getDateText()) {
            case "toDay":
                sql = "DATE(a.create_time) = CURDATE()";
                break;
            case "tomorrow":
                sql = "DATE_FORMAT(a.create_time,'%y%m%d') = DATE_FORMAT(CURDATE() - INTERVAL 1 DAY,'%y%m%d')";
                break;
            case "toWeek":
                sql = "YEAR(a.create_time) = YEAR(CURDATE()) AND WEEK(a.create_time) = WEEK(CURDATE())";
                break;
            case "lastMonth":
                sql = "DATE_FORMAT(a.create_time,'%y%m') =  DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH),'%y%m')";
                break;
            case "toQuarter":
                sql = "DATE_FORMAT(a.create_time, '%Y-%m') = CONCAT(YEAR(CURRENT_TIMESTAMP()), '-', QUARTER" +
                        "(CURRENT_TIMESTAMP())*3)";
                break;
            case "lastQuarter":
                sql = "QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) - 1";
                break;
            case "toYear":
                sql = "DATE_FORMAT(a.create_time,'%y%') = DATE_FORMAT(now(),'%y%')";
                break;
            case "lastYear":
                sql = "YEAR(a.create_time) = YEAR(CURDATE()) - 1";
                break;
        }
        indexBo.setUserId(SecurityUtils.getUserId());
        indexBo.setSearchDateSql("and " + sql);
        List<Map<String, Object>> allUsers = mapper.indexPaiHangBangSelf(indexBo);
        // 取前10条（如果不足10条，则取全部）
        List<Map<String, Object>> top10Users = allUsers.subList(0, Math.min(10, allUsers.size()));
        boolean hasCurrentUser = false;
        String targetUserId = SecurityUtils.getUserId(); // 你要查找的 userId

        for (Map<String, Object> user : top10Users) {
            if (targetUserId.equals(user.get("userId").toString())) {
                hasCurrentUser = true;
                break; // 找到后立即退出循环
            }
        }
        //如果不存在 就去找出当前用户
        if (!hasCurrentUser) {
            Map<String, Object> matchedUser = null;
            for (Map<String, Object> allUser : allUsers) {
                if (targetUserId.equals(allUser.get("userId").toString())) {
                    matchedUser = allUser;
                    break;  // 找到后立即退出循环
                }
            }
            if (null != matchedUser) {
                top10Users.add(matchedUser);
            }
        }
        return top10Users;
    }

    @Override
    public List<Map<String, Object>> indexPaiHangBangDept(IndexBo indexBo) {
        String sql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')";
        switch (indexBo.getDateText()) {
            case "toDay":
                sql = "DATE(a.create_time) = CURDATE()";
                break;
            case "tomorrow":
                sql = "DATE_FORMAT(a.create_time,'%y%m%d') = DATE_FORMAT(CURDATE() - INTERVAL 1 DAY,'%y%m%d')";
                break;
            case "toWeek":
                sql = "YEAR(a.create_time) = YEAR(CURDATE()) AND WEEK(a.create_time) = WEEK(CURDATE())";
                break;
            case "lastMonth":
                sql = "DATE_FORMAT(a.create_time,'%y%m') =  DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH),'%y%m')";
                break;
            case "toQuarter":
                sql = "DATE_FORMAT(a.create_time, '%Y-%m') = CONCAT(YEAR(CURRENT_TIMESTAMP()), '-', QUARTER" +
                        "(CURRENT_TIMESTAMP())*3)";
                break;
            case "lastQuarter":
                sql = "QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) - 1";
                break;
            case "toYear":
                sql = "DATE_FORMAT(a.create_time,'%y%') = DATE_FORMAT(now(),'%y%')";
                break;
            case "lastYear":
                sql = "YEAR(a.create_time) = YEAR(CURDATE()) - 1";
                break;
        }
        indexBo.setDeptId(SecurityUtils.getDeptId());
        indexBo.setSearchDateSql("and " + sql);
        List<Map<String, Object>> allDepts = mapper.indexPaiHangBangDept(indexBo);
        // 取前10条（如果不足10条，则取全部）
        List<Map<String, Object>> top10Depts = allDepts.subList(0, Math.min(10, allDepts.size()));
        boolean hasCurrentDept = false;
        String targetDeptId = SecurityUtils.getDeptId(); // 你要查找的 deptId
        for (Map<String, Object> dept : top10Depts) {
            if (targetDeptId.equals(dept.get("deptId").toString())) {
                hasCurrentDept = true;
                break; // 找到后立即退出循环
            }
        }
        //如果不存在 就去找出当前用户
        if (!hasCurrentDept) {
            Map<String, Object> matchedDept = null;
            for (Map<String, Object> allDept : allDepts) {
                if (targetDeptId.equals(allDept.get("deptId").toString())) {
                    matchedDept = allDept;
                    break;  // 找到后立即退出循环
                }
            }
            if (null != matchedDept) {
                top10Depts.add(matchedDept);
            }
        }
        return top10Depts;
    }

    @Override
    public Map<String, Objects> indexDaiCaoZuo(IndexBo indexBo) {
        return mapper.indexDaiCaoZuo(indexBo);
    }

    @Override
    @DataScope(userAlias = "aa", deptAlias = "aa")
    public List<Map<String, Objects>> xiansuofenxi(Customer customer) {
        return mapper.xiansuofenxi(customer);
    }

    @Override
    public boolean bizJinjianBillCaiWuConfirm(JinjianBill jinjianBill) {
        if (null != jinjianBill) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianBill.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-财务确认");
            customerDongtaiService.save(customerDongtai);
            jinjianBill.setCaiwuCheck("1");
            jinjianBill.setCheckTime(new Date());
            return this.save(jinjianBill);
        }
        return false;
    }
}
